export default {
	state:{
		shoppingCart: []
		// shoppingCart结构
		/* 
		shoppingCart = {
		  id: "", // 购物车id
		  productID: "", // 商品id
		  productName: "", // 商品名称
		  price: "", // 商品价格
		  num: "", // 商品数量
		  check: false // 是否勾选
		} */
	},
	getters: {
		// 获取购物车状态
		getShoppingCart (state) {
		  return state.shoppingCart;
		},
		// 购物车商品总数量
		getNum (state) {
		  let totalNum = 0;
			state.shoppingCart.forEach(item=>{
				 totalNum += item.num;
			})
		  return totalNum;
		},
		// 判断是否全选
		getIsAllCheck (state) {
		  let isAllCheck = true;
			return state.shoppingCart.every( (item, index) =>item.check == true)
		},
    // 获取勾选的商品信息
		getCheckGoods (state) {
		  // 用于确认订单页面
		  let checkGoods = [];
			state.shoppingCart.forEach(item=>{
				if (item.check) {
				  checkGoods.push(item);
				}
			})
		  return checkGoods;
		},
		// 获取购物车勾选的商品数量
		getCheckNum (state) {
		  let totalNum = 0;
			state.shoppingCart.forEach(item=>{
				if (item.check) {
				  totalNum += item.num;
				}
			})
		  return totalNum;
		},
		// 购物车勾选的商品总价格
		getTotalPrice (state) {
		  let totalPrice = 0;
			state.shoppingCart.forEach(item=>{
				if (item.check) {
				  totalPrice += item.price * item.num;
				}
			})
		  return totalPrice;
		}
	},
	mutations: {
		// 设置购物车状态
		setShoppingCart (state, data) {
		  state.shoppingCart = data;
		},
	
		// 添加购物车
		unshiftShoppingCart (state, data) {
		  state.shoppingCart.unshift(data);		  // 用于在商品详情页点击添加购物车,后台添加成功后，更新vuex状态
		},
	 
		// 更新购物车
		updateShoppingCart (state, payload) {
		  // 可更新 商品数量 和 是否勾选
		  if (payload.prop == "num") {
		    // 判断效果的商品数量是否小于1
		    if (payload.val < 1) {
		      return;
		    }
		  }
		  // 根据商品在购物车的数组的 索引 和 属性 更改
		  state.shoppingCart[payload.key][payload.prop] = payload.val;
		},
		
		// 根据购物车id删除购物车商品
		deleteShoppingCart (state, id) {
		  for (let i = 0; i < state.shoppingCart.length; i++) {
		    const temp = state.shoppingCart[i];
		    if (temp.id == id) {
		      state.shoppingCart.splice(i, 1);
		    }
		  }
		},
		
		// 点击全选按钮，更改每个商品的勾选状态
		checkAll (state, data) {
			state.shoppingCart.forEach(item=>{
				item.check = data;
			})
		}
	},
	actions: {
	  setShoppingCart ({ commit }, data) {
	    commit('setShoppingCart', data);
	  },
	  unshiftShoppingCart ({ commit }, data) {
	    commit('unshiftShoppingCart', data);
	  },
	  updateShoppingCart ({ commit }, payload) {
	    commit('updateShoppingCart', payload);
	  },
	  addShoppingCartNum ({ commit }, productID) {
	    commit('addShoppingCartNum', productID);
	  },
	  deleteShoppingCart ({ commit }, id) {
	    commit('deleteShoppingCart', id);
	  },
	  checkAll ({ commit }, data) {
	    commit('checkAll', data);
	  }
	}
}